﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using Openfree.Workflow.Common;

public partial class Controls_Activity_ProcessList : BaseUserControl
{
    public EventHandler OnProcessed;
    public EventHandler OnCancel;

    protected void Page_Load(object sender, EventArgs e)
    {
        ProcessRole1.OnProcessedSelectRole += On_ProcessedSelectRole;
        ProcessRole1.OnCancelSelectRole += On_CancelSelectRole;
    }


    public bool InitProcess(string instanceID, bool processVisibled)
    {
        literalProcess.Text = string.Empty;
        tbDescription.Text = string.Empty;

        bool buttonVisible = true;
        string cmdText = @"select a.*,
            (select top 1 Username from T_User where UserID= a.UserID) Username,
            (select top 1 Subject from T_SecurityRule where ContainerName = a.ActivityState ) ActivityStateName
            from T_WorkflowProcess a where InstanceID='{0}' order by CreateDate desc";
        DataSet ds = BaseAccess.GetDataSet(base.Connection, string.Format(cmdText, instanceID));
        literalProcess.Text = string.Empty;
        string htmlCode = string.Empty;
        ViewState["ActivityState"] = null;
        foreach (DataRow row in ds.Tables[0].Rows)  
        {
            if (row["UserID"].ToString() == SessionManager.UserID &&
                row["IsProcess"].ToString() == "False")
            {
                ViewState["ActivityState"] = row["ActivityState"].ToString();
                tbDescription.Text = row["Description"].ToString();
            }
            else
            {
                htmlCode = "\t<tr><td style=\"height:30px;\">{0}意见：</td><td style=\"font-size:14px;\">{1}于 {2} {3}了您的申请<br />{4}</td></tr>\r\n";
                object[] objs = new object[]{row["ActivityStateName"].ToString(),                 
                row["Username"].ToString(),
                DateTime.Parse(row["CreateDate"].ToString()).ToString("yyyy-MM-dd hh:ss"),
                GetProcessStateName(row["ProcessState"].ToString()),
                row["Description"].ToString().Replace("\r", "<br />")};
                literalProcess.Text += string.Format(htmlCode, objs);
            }
        }

        trDescription.Visible = processVisibled;
        hfInstanceID.Value = instanceID;
        hfReadOnly.Value = processVisibled.ToString();
        if (processVisibled)
        {
            InitButton(instanceID);
        }
        else
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                pnlView.Visible = false;
                buttonVisible = false;
            }
        }
        return buttonVisible;
    }

    private string GetProcessStateName(string processState)
    {
        string result = string.Empty;
        if ("Approve".Equals(processState))
        {
            result = "<b>同意</b>";
        }
        else if ("SendBack".Equals(processState))
        {
            result = "<b>退回</b>";
        }
        else if ("Reject".Equals(processState))
        {
            result = "<b>拒绝</b>";
        }
        return result;
    }

    private void InitButton(string instanceID)
    {
        ReadOnlyCollection<string> messageList = WorkflowManager.GetEventAllowed(new Guid(instanceID));
        if (messageList.Contains("Update")) btnUpdate.Visible = true;
        if (messageList.Contains("Approve")) btnApprove.Visible = true;
        if (messageList.Contains("SendBack")) btnSendBack.Visible = true;
        if (messageList.Contains("Reject")) btnReject.Visible = true;
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        //UpdateProcess();
        //WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        //workflowService.RaiseUpdateEvent(new Guid(hfInstanceID.Value), null);
        //UpdateProcessActivity();        
    }

    protected void btnApprove_Click(object sender, EventArgs e)
    {
        UpdateProcess("Approve", false);
        string processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
        if (ViewState["ActivityState"] != null &&
            processActivity.Equals(ViewState["ActivityState"].ToString()))
        {
            WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
            workflowService.RaiseApproveEvent(new Guid(hfInstanceID.Value), null);
        }
        UpdateApproveActivity();
    }

    protected void btnSendBack_Click(object sender, EventArgs e)
    {
        //UpdateProcess();
        //WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        //workflowService.RaiseSendBackEvent(new Guid(hfInstanceID.Value), null);
        //UpdateProcessActivity();
    }

    protected void btnReject_Click(object sender, EventArgs e)
    {
        UpdateProcess("Reject", true);
        WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        //UpdateProcessActivity();
        workflowService.RaiseRejectEvent(new Guid(hfInstanceID.Value), null);
        UpdateRejectActivity();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (OnCancel != null) OnCancel(sender, e);
    }

    private void UpdateProcess(string processState, bool isProcess)
    {
        string cmdText = "select * from T_WorkflowProcess where InstanceID='{0}' and UserID='{1}' and IsProcess=0";
        cmdText = string.Format(cmdText, hfInstanceID.Value, SessionManager.UserID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText, "T_WorkflowProcess");
        DataRow row = ds.Tables[0].Rows[0];
        ViewState["ActivityID"] = row["ActivityID"].ToString();
        row["IsProcess"] = isProcess;
        row["ProcessState"] = processState;
        row["Description"] = tbDescription.Text;
        BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowProcess", ds);

       
    }

    private void UpdateApproveActivity()
    {
        //RaiseEvent 之后需要有一定延迟，才能获取最新状态
        System.Threading.Thread.Sleep(1000);
        bool flag = true;
        try
        {
            //todo:最后一个状态执行结束，该工作流获取状态失败
            string processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
            string cmdText = "update T_Workflow set ProcessActivity ='{0}',ProcessDate='{1}' where InstanceID='{2}'";
            cmdText = string.Format(cmdText, processActivity, DateTime.Now, hfInstanceID.Value);
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);

            pnlView.Visible = false;
            pnlRole.Visible = true;

            ProcessRole1.InitDataByProcess(hfInstanceID.Value, processActivity, ViewState["ActivityID"].ToString());
            flag = false;
        }
        catch { }

        if (flag)
        {
            //todo:最后一个状态执行结束，该工作流获取状态失败
            UpdateProcess("Approve", true);

            string cmdText = "update T_Workflow set ProcessDate='{0}' where InstanceID='{1}'";
            cmdText = string.Format(cmdText, DateTime.Now, hfInstanceID.Value);
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);

            if (OnProcessed != null) OnProcessed(null, null);
        }
        
    }

    private void UpdateRejectActivity()
    {
            string cmdText = "update T_Workflow set ProcessDate='{0}' where InstanceID='{1}'";
            cmdText = string.Format(cmdText,
                DateTime.Now, hfInstanceID.Value);
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        if (OnProcessed != null) OnProcessed(null, null);
    }

    protected virtual void On_ProcessedSelectRole(object sender, EventArgs e)
    {
        pnlView.Visible = true;
        pnlRole.Visible = false;
        if (OnProcessed != null) OnProcessed(null, null);
    }

    protected virtual void On_CancelSelectRole(object sender, EventArgs e)
    {
        pnlView.Visible = true;
        pnlRole.Visible = false;
        if (OnProcessed != null) OnProcessed(null, null);
    }
}
